package com.polytech.diploma.SQLGenerator.Oracle.Functions;

import java.util.List;
import java.util.Map;

import com.polytech.diploma.SQLGenerator.Oracle.Node;
import com.polytech.diploma.SQLGenerator.Oracle.Arguments.Argument;
import com.polytech.diploma.SQLGenerator.Oracle.Conditions.ConditionArgument;

public class CaseExpression implements Expression {
	protected Argument caseField = null;
	protected Map<ConditionArgument, Argument> caseWhenClause = null;	
	protected Argument caseElseClause = null;
	//protected FunctionType type;
	
	private CaseExpression(Builder builder) {
		super();
		this.caseField = builder.caseField;
		this.caseWhenClause = builder.caseWhenClause;
		this.caseElseClause = builder.caseElseClause;
	}
	
	public static class Builder{
		private Argument caseField = null;
		private Map<ConditionArgument, Argument> caseWhenClause;	
		private Argument caseElseClause = null;
		public Builder setCaseField(Argument caseField) {
			this.caseField = caseField;
			return this;
		}
		public Builder setCaseWhenClause(Map<ConditionArgument, Argument> caseWhenClause) {
			this.caseWhenClause = caseWhenClause;
			return this;
		}
		public Builder setCaseElseClause(Argument caseElseClause) {
			this.caseElseClause = caseElseClause;
			return this;
		}
		public CaseExpression build()
		{
			return new CaseExpression(this);
		}
	}

	public void setCaseField(Argument caseField) {
		this.caseField = caseField;
	}

	public void setCaseWhenClause(Map<ConditionArgument, Argument> caseWhenClause) {
		this.caseWhenClause = caseWhenClause;
	}

	public void setCaseElseClause(Argument caseElseClause) {
		this.caseElseClause = caseElseClause;
	}

	@Override
	public Map<String, List<String>> getTablesWithFields(
			Map<String, List<String>> fieldMap) {
		if(caseField != null)
			fieldMap = caseField.getTablesWithFields(fieldMap);
		
		if(caseWhenClause != null)
		{
			for(ConditionArgument conditionArgument : caseWhenClause.keySet())
			{
				fieldMap = conditionArgument.getTablesWithFields(fieldMap);
			}
			
			for(Argument arg : caseWhenClause.values())
			{
				fieldMap = arg.getTablesWithFields(fieldMap);
			}
		}
		
		if(caseElseClause != null)
			fieldMap = caseElseClause.getTablesWithFields(fieldMap);
		
		return fieldMap;
	}
	
}
